package com.ruoyi.camera.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.baidu.ai.aip.controller.EasydlObjectDetection;
import com.ruoyi.camera.domain.AiCamera;
import com.ruoyi.camera.service.IAiCameraService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.json.JSON;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;

/**
 * 摄像头识别Controller
 *
 * @author ruoyi
 * @date 2024-02-26
 */
@Controller
@RequestMapping("/AI/cameraB")
public class AiCameraBController extends BaseController
{
    private String prefix = "AI/cameraB";

    @Autowired
    private IAiCameraService aiCameraService;

    @Autowired
    private EasydlObjectDetection easydlObjectDetection ;

    @RequiresPermissions("AI:cameraB:view")
    @GetMapping()
    public String camera()
    {
        return prefix + "/cameraB";
    }

    /**
     * 查询摄像头识别列表
     */
    @RequiresPermissions("AI:cameraB:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AiCamera aiCamera)
    {
        startPage();
        List<AiCamera> list = aiCameraService.selectAiCameraList(aiCamera);
        return getDataTable(list);
    }

    /**
     * 导出摄像头识别列表
     */
    @RequiresPermissions("AI:cameraB:export")
    @Log(title = "摄像头识别", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AiCamera aiCamera)
    {
        List<AiCamera> list = aiCameraService.selectAiCameraList(aiCamera);
        ExcelUtil<AiCamera> util = new ExcelUtil<AiCamera>(AiCamera.class);
        return util.exportExcel(list, "摄像头识别数据");
    }

    /**
     * 新增摄像头识别
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存摄像头识别
     */
    @RequiresPermissions("AI:cameraB:add")
    @Log(title = "摄像头识别", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AiCamera aiCamera )
    {
        if (aiCamera.getPhoto().contains("data:")) {
            int start = aiCamera.getPhoto().indexOf(",");
            String file = aiCamera.getPhoto().substring(start + 1);
            final byte[] decode = Base64.getDecoder().decode(file);// 解码得到原始数据

            FileOutputStream fileOutStream = null; // 创建输出流
            try {
                fileOutStream = new FileOutputStream("capture/capture.png");
                fileOutStream.write(decode); // 写入文件
                fileOutStream.close(); // 关闭输出流
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        final String json = easydlObjectDetection.easydlObjectDetection("capture/capture.png",aiCamera.getRate());
        final Map json2Map = (Map)JSONUtils.parse(json);
        if(json2Map.containsKey("error_code")){
            return AjaxResult.success("错误码：336005,图片获取失败,请重新截取图片");
        }
        if(json2Map.containsKey("results")){
            final List<Object> results = (List<Object>) json2Map.get("results");
            if(results.size() == 0){
                return AjaxResult.success("抓取失败，物品型号未添加或调整物品位置");
            }else {
                return AjaxResult.success(results.get(0));
            }

        }

        return AjaxResult.success(json);
    }

    /**
     * 修改摄像头识别
     */
    @RequiresPermissions("AI:cameraB:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        AiCamera aiCamera = aiCameraService.selectAiCameraById(id);
        mmap.put("aiCamera", aiCamera);
        return prefix + "/edit";
    }

    /**
     * 修改保存摄像头识别
     */
    @RequiresPermissions("AI:cameraB:edit")
    @Log(title = "摄像头识别", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AiCamera aiCamera)
    {
        return toAjax(aiCameraService.updateAiCamera(aiCamera));
    }

    /**
     * 删除摄像头识别
     */
    @RequiresPermissions("AI:cameraB:remove")
    @Log(title = "摄像头识别", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(aiCameraService.deleteAiCameraByIds(ids));
    }
}
